const CFG= require('../config');
const EC = require('../comm/err-code');
const tbDevice = require('../model/tb_device');
const FUN = require('../comm/func');
const helper = require('../comm/api-helper');
const express = require('express');
const api = express();


// 生成免费的用户设备，一个用户3个
api.post('/gen-free-devs', async(req, resp)=>{
  let param = req.body;
  let ret = {code:EC.FAILD, msg:EC.FAILD_MSG};

  // 合法性校验
  let uInfo = await helper.CheckToken(param.token);
  if(!uInfo.uid) return resp.json({code:EC.AUTH_ERR, msg:EC.AUTH_ERR_MSG});

  // 新增设备记录
  let devsData = [];
  let devIdStart = CFG.USER_FREE_HWID_START + uInfo.uid*100 + 1;
  for(let i=0; i<3; i++) {
    let hwid = devIdStart + i;
    let hwTypeName = FUN.Hwid2TypeName(hwid);
    let affected = await tbDevice.newUserDev(uInfo.uid, hwid, FUN.Hwid2TypeNum(hwid));
    if (affected == 0) {
      ret.code = EC.FAILD;
      ret.msg = EC.FAILD_MSG;
      return resp.json(ret);
    }
    devsData.push({
      'hwid': hwid,
      'username': FUN.Hwid2TypeName(hwid),
      'password': CFG.GetDevAuthCode(hwid),
      'clientid': FUN.Hwid2TypeName(hwid)+'.'+hwid,
      'topic': `0/${hwTypeName}/var/0-${hwid}<br>0/${hwTypeName}/rx/${hwid}<br>0/${hwTypeName}/tx/${hwid}`,
    })
    console.log(" - reg free dev [%d] ok", hwid);
  }
  helper.DevUpdateNotify('mqsrv_clean_dev_list');

  ret.code = EC.SUCESS;
  ret.msg = EC.SUCESS_MSG;
  ret.data = devsData;
  resp.json(ret);
})

// 查询若干设备所有信息，只能查归属自己的
api.post('/get-devs-info', async(req, resp)=>{
  let param = req.body;
  let res = {code:EC.FAILD, msg:EC.FAILD_MSG};

  // 合法性校验
  let uInfo = await helper.CheckToken(param.token);
  if(!uInfo.uid) return resp.json({code:EC.AUTH_ERR, msg:EC.AUTH_ERR_MSG});

  // 参数校验
  if(!param.ids) return resp.json({code:EC.PARAM_ERROR, msg:EC.PARAM_ERROR_MSG});

  let hwids = param.ids.split(',');
  for (hwid of hwids) { // 轮询查询设备
    let devInfo = await tbDevice.find(hwid);
    if (devInfo == null) { // 设备不存在
      res.code = EC.DEV_NON_EXISTENT;
      res.msg = EC.DEV_NON_EXISTENT_MSG;
      if(hwids.length == 1) return resp.json(res);
      else continue;
    }

    // uid不对
    if(devInfo.uid != 0 && devInfo.uid != uInfo.uid){
      res.code = EC.AUTH_ERR;
      res.msg = EC.AUTH_ERR_MSG;
      if(hwids.length == 1) return resp.json(res);
      else continue;
    }

    // 设备存在，返回设备信息
    res.code = EC.SUCESS;
    res.msg = EC.SUCESS_MSG;
    if(!res.data) res.data = [];
    res.data.push(devInfo);
  }

  resp.json(res);
})

// 查询自己的设备信息
api.post('/get-my-dev-info', async(req, resp)=>{
  let param = req.body;
  let ret = {code:EC.FAILD, msg:EC.FAILD_MSG};

  // 合法性校验
  let uInfo = await helper.CheckToken(param.token);
  if(!uInfo.uid) return resp.json({code:EC.AUTH_ERR, msg:EC.AUTH_ERR_MSG});

  let devsData = [];
  let devsInfo = await tbDevice.getMyAllDevsInfo(uInfo.uid);
  for (let d of devsInfo) {
    let hwTypeName = FUN.Hwid2TypeName(d.hwid);
    devsData.push({
      'hwid': d.hwid,
      'username': FUN.Hwid2TypeName(d.hwid),
      'password': CFG.GetDevAuthCode(d.hwid),
      'clientid': FUN.Hwid2TypeName(d.hwid)+'.'+d.hwid,
      'topic': `0/${hwTypeName}/var/0-${d.hwid}<br>0/${hwTypeName}/rx/${d.hwid}<br>0/${hwTypeName}/tx/${d.hwid}`,
    })
  }

  ret.code = EC.SUCESS;
  ret.msg = EC.SUCESS_MSG;
  ret.data = devsData;
  resp.json(ret);
})

// 查询自己的设备数量
api.post('/get-my-dev-num', async(req, resp)=>{
  let param = req.body;
  let res = {code:EC.FAILD, msg:EC.FAILD_MSG};

  // 合法性校验
  let uInfo = await helper.CheckToken(param.token);
  if(!uInfo.uid) return resp.json({code:EC.AUTH_ERR, msg:EC.AUTH_ERR_MSG});

  res.num = await tbDevice.getMyAllDevsNum(uInfo.uid);
  res.code = EC.SUCESS;
  res.msg = EC.SUCESS_MSG;
  resp.json(res);
})

// 管理接口：获取db所有设备，无uid要求
api.post('/get-all', async(req, resp)=>{
  let param = req.body;
  let res = {code:EC.FAILD, msg:EC.FAILD_MSG};

  // 合法性校验
  let uInfo = await helper.CheckToken(param.token);
  if(!uInfo.uid) return resp.json({code:EC.AUTH_ERR, msg:EC.AUTH_ERR_MSG});

  // 权限校验
  let auth = await helper.CheckAuth(param.token, 'dev');
  if (!auth) return resp.json({code:EC.AUTH_ERR, msg:EC.AUTH_ERR_MSG});

  let itemInfo = await tbDevice.getAllDev(param.page, param.limit);
  if(itemInfo == null){
    return resp.json({code:EC.PARAM_ERROR, msg:EC.PARAM_ERROR_MSG});
  }

  res.code = EC.SUCESS;
  res.msg = EC.SUCESS_MSG;
  res.data = itemInfo;
  resp.json(res);
})

// 管理接口：查询设备，无uid要求
api.post('/query-info', async(req, resp)=>{
  let param = req.body;
  let res = {code:EC.FAILD, msg:EC.FAILD_MSG};

  // 合法性校验
  let uInfo = await helper.CheckToken(param.token);
  if(!uInfo.uid) return resp.json({code:EC.AUTH_ERR, msg:EC.AUTH_ERR_MSG});

  // 权限校验
  let auth = await helper.CheckAuth(param.token, 'dev');
  if (!auth) return resp.json({code:EC.AUTH_ERR, msg:EC.AUTH_ERR_MSG});

  // 参数校验
  if(!param.hwid || !param.type) return resp.json({code:EC.PARAM_ERROR, msg:EC.PARAM_ERROR_MSG});

  // 序列号类型不对
  let typeNum = FUN.Hwid2TypeNum(param.hwid);
  if (param.type != typeNum) {
    res.code = EC.DEV_TYPE_ERR;
    res.msg = EC.DEV_TYPE_ERR_MSG;
    res.type = typeNum;
    return resp.json(res);
  }

  // 查询设备
  let devInfo = await tbDevice.find(param.hwid);
  if (devInfo != null) { // 设备存在，返回设备信息
    res.code = EC.DEV_ALREADY_EXISTS;
    res.msg = EC.DEV_ALREADY_EXISTS_MSG;
    res.data = devInfo;
    return resp.json(res);
  }

  // 设备不存在，返回注册码
  res.code = EC.SUCESS;
  res.msg = EC.SUCESS_MSG;
  res.auth = CFG.GetDevAuthCode(param.hwid);
  resp.json(res);
})

// 管理接口：管理员注册登记新设备
api.post('/reg-new', async(req, resp)=>{
  let param = req.body;
  let res = {code:EC.FAILD, msg:EC.FAILD_MSG};

  // 合法性校验
  let uInfo = await helper.CheckToken(param.token);
  if(!uInfo.uid) return resp.json({code:EC.AUTH_ERR, msg:EC.AUTH_ERR_MSG});

  // 权限校验
  let auth = await helper.CheckAuth(param.token, 'dev');
  if (!auth) return resp.json({code:EC.AUTH_ERR, msg:EC.AUTH_ERR_MSG});

  // 参数校验
  if(!param.hwid || !param.type) return resp.json({code:EC.PARAM_ERROR, msg:EC.PARAM_ERROR_MSG});

  // 查询设备
  let devInfo = await tbDevice.find(param.hwid);
  if (devInfo != null) { // 设备已经存在
    res.code = EC.DEV_ALREADY_EXISTS;
    res.msg = EC.DEV_ALREADY_EXISTS_MSG;
    res.data = devInfo;
    return resp.json(res);
  }

  // 密钥校验，省略

  // 序列号类型不对
  if (param.type != FUN.Hwid2TypeNum(param.hwid)) {
    res.code = EC.DEV_TYPE_ERR;
    res.msg = EC.DEV_TYPE_ERR_MSG;
    return resp.json(res);
  }

  // 新增设备记录
  let affected = await tbDevice.newDev(param.hwid, param.type);
  if (affected == 0) {
    res.code = EC.FAILD;
    res.msg = EC.FAILD_MSG;
    return resp.json(res);
  }

  console.log(" - reg new dev [%d] ok", param.hwid);
  helper.DevUpdateNotify('mqsrv_clean_dev_list');

  res.code = EC.SUCESS;
  res.msg = EC.SUCESS_MSG;
  resp.json(res);
})

// 用户激活自由设备
api.post('/active-dev', async(req, resp)=>{
  let param = req.body;
  let res = {code:EC.FAILD, msg:EC.FAILD_MSG};

  // 合法性校验
  let uInfo = await helper.CheckToken(param.token);
  if(!uInfo.uid) return resp.json({code:EC.AUTH_ERR, msg:EC.AUTH_ERR_MSG});

  // 参数校验
  if(!isNum(param.hwid) || parseInt(param.hwid) == 0) return resp.json({code:EC.PARAM_ERROR, msg:EC.PARAM_ERROR_MSG});

  // 密钥校验，省略

  // 只能激活uid为0，或者自己的设备
  let devInfo = await tbDevice.find(param.hwid);
  if (!devInfo) {
    return resp.json({code:EC.DEV_NON_EXISTENT, msg:EC.DEV_NON_EXISTENT_MSG});
  }

  if (devInfo.uid == uInfo.uid) {
    return resp.json({code:EC.SUCESS, msg:EC.SUCESS_MSG});
  } else if (devInfo.uid != 0) {
    return resp.json({code:EC.DEV_OWNER_NOT_YOU, msg:EC.DEV_OWNER_NOT_YOU_MSG});
  }

  // 激活
  tbDevice.updateDev(param.hwid, {uid:uInfo.uid});
  helper.DevUpdateNotify('mqsrv_clean_dev_list');

  // todo 激活产品

  res.code = EC.SUCESS;
  res.msg = EC.SUCESS_MSG;
  resp.json(res);
})

// 用户重置设备，清除conn id，清除uid
api.post('/reset-dev', async(req, resp)=>{
  let param = req.body;
  let res = {code:EC.FAILD, msg:EC.FAILD_MSG};

  // 合法性校验
  let uInfo = await helper.CheckToken(param.token);
  if(!uInfo.uid) return resp.json({code:EC.AUTH_ERR, msg:EC.AUTH_ERR_MSG});

  // 参数校验
  if(!isNum(param.hwid) || parseInt(param.hwid) == 0) return resp.json({code:EC.PARAM_ERROR, msg:EC.PARAM_ERROR_MSG});

  // 查询设备
  let devInfo = await tbDevice.find(param.hwid);
  if (devInfo == null) { // 设备不存在
    res.code = EC.DEV_NON_EXISTENT;
    res.msg = EC.DEV_NON_EXISTENT_MSG;
    return resp.json(res);
  }

  // uid不对
  if(devInfo.uid != 0 && devInfo.uid != uInfo.uid) {
    res.code = EC.AUTH_ERR;
    res.msg = EC.AUTH_ERR_MSG;
    return resp.json(res);
  }

  // 设备存在，修改conn_id为空
  tbDevice.updateDev(param.hwid, {conn_id:'', uid:uInfo.uid}); // uid暂时不清
  helper.DevUpdateNotify('mqsrv_clean_dev_list');

  res.code = EC.SUCESS;
  res.msg = EC.SUCESS_MSG;
  resp.json(res);
})

// 获取日志
api.post('/get-log', async(req, resp)=>{
  let param = req.body;
  let res = {code:EC.FAILD, msg:EC.FAILD_MSG};

  // 合法性校验
  let uInfo = await helper.CheckToken(param.token);
  if(!uInfo.uid) return resp.json({code:EC.AUTH_ERR, msg:EC.AUTH_ERR_MSG});

  // 参数校验
  if(!param.hwid) return resp.json({code:EC.PARAM_ERROR, msg:EC.PARAM_ERROR_MSG});

  // 查询设备
  res.total = await tbDevice.getDevLogsTotal(uInfo.uid, param.hwid);
  res.data = await tbDevice.getDevLogs(uInfo.uid, param.hwid, param.page, param.limit);

  res.code = EC.SUCESS;
  res.msg = EC.SUCESS_MSG;
  return resp.json(res);
})

// 清除日志
api.post('/clean-log', async(req, resp)=>{
  let param = req.body;
  let res = {code:EC.FAILD, msg:EC.FAILD_MSG};

  // 合法性校验
  let uInfo = await helper.CheckToken(param.token);
  if(!uInfo.uid) return resp.json({code:EC.AUTH_ERR, msg:EC.AUTH_ERR_MSG});

  // 参数校验
  if(!param.hwid) return resp.json({code:EC.PARAM_ERROR, msg:EC.PARAM_ERROR_MSG});

  // 查询设备
  await tbDevice.cleanDevLogs(uInfo.uid, param.hwid);

  res.code = EC.SUCESS;
  res.msg = EC.SUCESS_MSG;
  return resp.json(res);
})

module.exports=api;